<?php

include dirname(dirname(__FILE__)) . '/include/common.php';

class webServiceLogin extends core {

    public function process() {
        /* CHECK EMAIL */

        if (!isset($_POST['userEmail'])) {
            $this->_response('ERROR::The email is empty');
        }

        $email = $this->_cleanEmail($_POST['userEmail']);

        if (!$email) {
            $this->_response('ERROR::The email is empty');
        }

        if (!isset($_POST['password'])) {
            $this->_response('ERROR::The password is empty');
        }

        $password = md5($_POST['password']);

        if (isset($_POST['pushtoken'])) {
            $device_token = trim($_POST['pushtoken']);
            $token_type = 'pushtoken';
        } else if (isset($_POST['udid'])) {
            $device_token = trim($_POST['udid']);
            $token_type = 'udid';
        } else {
            $this->_response('Oops, something went wrong. Please try again');
        }

        if (!$device_token) {
            $this->_response('Oops, something went wrong. Please try again');
        }

        $user = $this->db->get_row("SELECT * FROM users WHERE email LIKE '{$this->db->escape($email)}' LIMIT 1");

        if (!$user) {
            $this->_response(4);
        }
        
        if ($user->active != 1) {
            $this->_response(2);
        }

        if ($user->password != $password) {
            $this->_response(3);
        }
        
        if (!$user->token)
        {
            $token = uniqid('', true);
            if (! $this->db->query("UPDATE `users` SET token = '$token'")) {
                $this->_response('ERROR::Generate unique token failed.');
            }
            $user->token = $token;
        }

        $insert_profile = false;
        
        $device = $this->db->get_row("SELECT * FROM devices WHERE device_token LIKE '{$this->db->escape($device_token)}' LIMIT 1");

        if (! $device) {
            $fields = array();
            $values = array();

            $this->_preDataForInsert(
                    array(           
                        'device_token' => $device_token,
                        'token_type' => $token_type
                    ), $fields, $values);

            $fields = implode(',', $fields);
            $values = implode(',', $values);

            if (! $this->db->query("INSERT INTO `devices` ({$fields}) VALUES ({$values});")) {
                $this->_response('ERROR::Insert device to DB is failed');
            }
            
            $device_id = $this->db->insert_id;
            
            $insert_profile = true;
        } else {
            $device_id = $device->device_id;
        }
        
        if(! $insert_profile) {
            $profile = $this->db->get_row("SELECT * FROM user_device WHERE device_id = '{$device_id}' AND `user_id` = '{$user->id}' LIMIT 1");

            if ($profile) {         
                $profile_id = $profile->profile_id;
            } else {
                $insert_profile = true;
            }
        }
        
        if($insert_profile) {
            $fields = array();
            $values = array();

            $this->_preDataForInsert(
                    array(           
                        'device_id' => $device_id,
                        'user_id' => $user->id,
                        'online' => 1
                    ), $fields, $values);

            $fields = implode(',', $fields);
            $values = implode(',', $values);

            if (! $this->db->query("INSERT INTO `user_device` ({$fields}) VALUES ({$values});")) {
                $this->_response('ERROR::Insert profile to DB is failed');
            }
            
            $profile_id = $this->db->insert_id;
        } else {
            $this->db->query("UPDATE `user_device` SET `online` = 0 WHERE device_id = '{$device_id}'");
            
            $this->db->query("UPDATE `user_device` SET `online` = 1 WHERE profile_id = '{$profile_id}' LIMIT 1;");
        }
        $work_location=0;
		if($user->location_id ==1){
			$work_location= 1;
		}
       $registration_id = $this->db->get_var("SELECT registration_id FROM devices d join user_device ud on ud.device_id=d.device_id where profile_id=".$profile_id);
          $this->_JSONResponse(array('results' => array('userID'=>$user->id,'email'=>$user->email,'token'=>$user->token, 'profileID' => $profile_id, 'firstName' => $user->first_name, 'lastName' => $user->last_name,'userRole' => $user->user_role,'registrationID'=>$registration_id)));
    }

}

$processor = new webServiceLogin();
$processor->process();
?>